<template>
  <div class="register-container">
    <div class="register-box">
      <!-- Logo部分 -->
      <div class="logo-container">
        <img src="@/assets/logo.png" alt="Logo" class="logo">
        <h2 class="title">微信管理系统</h2>
      </div>

      <!-- 注册表单 -->
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
          />
        </el-form-item>

        <el-form-item prop="verificationCode">
          <el-input
            v-model="registerForm.verificationCode"
            placeholder="请输入验证码"
            @keyup.enter="handleRegister"
          >
            <template #append>
              <el-button
                type="text"
                :disabled="countdown > 0"
                @click="getVerificationCode"
                style="color: #409EFF;"
              >
                {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item class="register-button">
          <el-button
            :loading="loading"
            type="primary"
            class="register-submit"
            @click="handleRegister"
          >
            注 册
          </el-button>
        </el-form-item>

        <div class="login-link">
          已有账号？<router-link to="/login">去登录</router-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const loading = ref(false)
const registerFormRef = ref<FormInstance>()

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  phone: '',
  verificationCode: ''
})

// 验证码倒计时
const countdown = ref(0)
const timer = ref<NodeJS.Timeout | null>(null)

// 自定义校验规则 - 确认密码
const validateConfirmPassword = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

// 自定义校验规则 - 手机号
const validatePhone = (rule: any, value: string, callback: any) => {
  const phoneRegex = /^1[3-9]\d{9}$/
  if (value === '') {
    callback(new Error('请输入手机号'))
  } else if (!phoneRegex.test(value)) {
    callback(new Error('请输入正确的手机号格式'))
  } else {
    callback()
  }
}

// 自定义校验规则 - 验证码
const validateVerificationCode = (rule: any, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入验证码'))
  } else if (value !== '1234') {
    callback(new Error('验证码错误，请输入1234'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { validator: validateVerificationCode, trigger: 'blur' }
  ]
}

// 获取验证码
const getVerificationCode = async () => {
  // 先验证手机号格式是否正确
  if (!registerForm.phone) {
    ElMessage.warning('请输入手机号')
    return
  }
  
  const phoneRegex = /^1[3-9]\d{9}$/
  if (!phoneRegex.test(registerForm.phone)) {
    ElMessage.warning('请输入正确的手机号格式')
    return
  }
  
  // 禁用真实验证码发送，默认使用1234
  ElMessage.success('验证码已发送，默认验证码为：1234')
  // 开始倒计时
  startCountdown()
}

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60
  
  if (timer.value) {
    clearInterval(timer.value)
  }
  
  timer.value = setInterval(() => {
    if (countdown.value > 0) {
      countdown.value--
    } else {
      if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
      }
    }
  }, 1000)
}

// 注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('注册请求开始发送')
        // 创建URLSearchParams对象序列化参数
        const params = new URLSearchParams();
        params.append('username', registerForm.username);
        params.append('password', registerForm.password);
        params.append('phone', registerForm.phone);
        params.append('phone_code', registerForm.verificationCode);
        const requestData = {
          username: registerForm.username,
          password: registerForm.password,
          phone: registerForm.phone,
          phone_code: registerForm.verificationCode
        };
        
        // 调用注册接口
        const response = await axios.post('/register', requestData, {
          headers: {
            'Content-Type': 'application/json'
          }
        })
        
        console.log('注册请求响应:', response)
        if (response.data.code === 200) {
          ElMessage.success('注册成功，请登录')
          console.log('即将跳转到登录页面')
          router.push('/login')
        } else {
          console.log('注册失败，状态码:', response.data.code)
          ElMessage.error(response.data.msg || '注册失败')
        }
      } catch (error: any) {
        console.error('注册请求异常:', error)
        if (error.response) {
          console.error('响应错误:', error.response)
        } else if (error.request) {
          console.error('请求错误:', error.request)
        } else {
          console.error('其他错误:', error.message)
        }
        ElMessage.error(error.response?.data?.msg || '注册失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped lang="scss">
.register-container {
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;

  .register-box {
    width: 400px;
    padding: 40px;
    background: rgba(255, 255, 255, 0.9);
    border-radius: 12px;
    box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    backdrop-filter: blur(10px);

    .logo-container {
      text-align: center;
      margin-bottom: 30px;

      .logo {
        width: 80px;
        height: 80px;
        margin-bottom: 16px;
      }

      .title {
        font-size: 24px;
        color: #333;
        margin: 0;
      }
    }

    .register-form {
      .el-input {
        --el-input-height: 44px;
        margin-bottom: 5px;
      }

      .register-button {
        margin-top: 30px;
        
        .register-submit {
          width: 100%;
          height: 44px;
          font-size: 16px;
        }
      }
    }

    .login-link {
      text-align: center;
      margin-top: 16px;
      font-size: 14px;
      
      a {
        color: #409EFF;
        text-decoration: none;
        
        &:hover {
          text-decoration: underline;
        }
      }
    }
  }
}
</style>